import axios from 'axios'

axios.defaults.timeout = 20000; //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json'; //配置请求头
axios.defaults.headers.put['Content-Type'] = 'application/json'; //配置请求头

// axios.defaults.baseURL = 'http://192.168.0.47:8889/pepsi-member-service'; //本地环境
axios.defaults.baseURL = 'http://39.103.239.44:8080/pepsi-member-service'; //测试环境
// axios.defaults.baseURL = 'http://8.142.67.91:8080/pepsi-member-service';   //线上环境

axios.defaults.headers.common['token'] = sessionStorage.getItem('authorization'); // 请求头获取token

//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {

    // 在发送请求之前做某件事   请求头携带token  解决不刷新浏览器 不携带token
    if (sessionStorage.getItem("authorization") != null) {
        config.headers["token"] = sessionStorage.getItem("authorization");
    }

    if (config.method === 'post') {
        config.data = JSON.stringify(config.data);
    }
    if (config.method === 'put') {
        config.data = JSON.stringify(config.data);
    }
    return config;
}, (error) => {
    console.log('错误的传参')
    return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
    console.log(res, "3333333333333");
    //对响应数据做些事
    if (!res.data.success) {
        return Promise.resolve(res);
    }
    return res;
}, (error) => {
    console.log('网络异常')
    return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

// 返回一个Promise(发送get请求)
export function fetchGet(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: param
            })
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

// 返回一个Promise(发送put请求)
export function fetchPut(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

// 返回一个Promise(发送delete请求)
export function fetchDelete(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, params)
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}


export default {
    fetchPost,
    fetchGet,
    fetchPut,
    fetchDelete
}